<script setup lang="ts">
import { onUnmounted, reactive, ref, watch } from 'vue';
import mammoth from 'mammoth';
import _ from 'underscore';
import { useDialog } from 'naive-ui';
import AddImg from '@/assets/imgs/icon-catalog-add.png';
import EditImg from '@/assets/imgs/icon-catalog-edit.png';
import WriteImg from '@/assets/imgs/icon-catalog-write.png';
import DeleteImg from '@/assets/imgs/icon-catalog-delete.png';
import CompleteImg from '@/assets/imgs/icon-complete.png';
import IncompleteImg from '@/assets/imgs/icon-incomplete.png';
import DeleteLabel01Img from '@/assets/smart-eye/icon-delete-01.png';
import DeleteLabel02Img from '@/assets/smart-eye/icon-delete-02.png';
import DeleteLabel03Img from '@/assets/smart-eye/icon-delete-03.png';
import DeleteLabel04Img from '@/assets/smart-eye/icon-delete-04.png';
import DeleteLabel05Img from '@/assets/smart-eye/icon-delete-05.png';
import EditLabel01Img from '@/assets/smart-eye/icon-edit-01.png';
import EditLabel02Img from '@/assets/smart-eye/icon-edit-02.png';
import EditLabel03Img from '@/assets/smart-eye/icon-edit-03.png';
import EditLabel04Img from '@/assets/smart-eye/icon-edit-04.png';
import EditLabel05Img from '@/assets/smart-eye/icon-edit-05.png';
import { escapeHTMLManually, getImageInfoFromBase64, successMessage } from '@/utils/utils';
import EditLabel from '@/views/smart-eye/detail/modules/edit-label.vue';
import { useBoolean } from '~/packages/hooks';
import { labelBindingDeleteAction } from '@/service/api';

interface Props {
  analysisType?: number; // 1.新建；2.编辑（查看）
  logId?: number;
  filePath?: string;
  fileName?: string;
  labelList?: any[];
  isBack?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  analysisType: 0,
  logId: 0,
  filePath: '',
  fileName: '',
  labelList: () => [],
  isBack: false
});

const showLoading = ref<boolean>(false);
const loadingDes = ref<string>('文档较大，正在努力处理中，请稍后...');

const { bool: showEditLabelModal, setTrue: openEditLabelModal } = useBoolean();

const contentHtml = ref<string>('');
const docContentHtml = ref<string>('');
const imgList = ref<any[]>([]);
const IMAGE_TAG: string = 'IMAGE_TAG';

const labelType = ref<number>(0); // 0.编辑；1.新增；2.新增自选
const labelObj = ref<any>();

// 编辑器配置
const editorConfig: object = reactive({
  serverUrl: '',
  UEDITOR_HOME_URL: '/modules/bidWriting/UEditorPlus/',
  UEDITOR_CORS_URL: '/modules/bidWriting/UEditorPlus/',
  toolbars: [],
  autoFloatEnabled: false,
  readonly: true,
  autoSaveEnable: false, // 禁用自动保存
  elementPathEnabled: false, // 禁用元素路径
  initialFrameHeight: '610',
  autoHeightEnabled: false, // 禁止编辑器自动长高
  maximumWords: 2000000
});

// 引入的js文件，这里是一定要写的。
const editorDependencies: string[] = reactive(['ueditor.config.js', 'ueditor.all.js', 'lang/zh-cn/zh-cn.js']);

const ueditor = ref<any | null>(null);

watch(
  () => props.labelList,
  value => {
    if (value) {
      if (ueditor.value) {
        getLabelAction();
      }
    }
  },
  { deep: true }
);

watch(
  () => props.isBack,
  value => {
    if (value) {
      if (ueditor.value) {
        ueditor.value.destroy();
        ueditor.value = null;
      }
    }
  }
);

// 定义方法并定义好返回值的格式
interface Emits {
  (e: 'refresh'): void;
}

// defineEmits 不用单独引入，是全局默认引入的
const emit = defineEmits<Emits>();

function readyHandle(editor: any) {
  ueditor.value = editor;

  // 监听内容变化
  ueditor.value.addListener('updateSections', getCatalogHandle);

  // 监听内容变化
  editor.addListener('contentchange', () => {
    // console.log('编辑器内容发生改变');
  });

  if (props.analysisType === 1) {
    // 获取iframe的document对象
    // 获取编辑器iframe
    const iframe = editor.iframe;
    const iframeDoc = iframe.contentDocument || iframe.contentWindow.document;

    // 为iframe的document添加点击事件监听
    iframeDoc.addEventListener('click', (e: any) => {
        // console.log('1e: ', e.target.parentNode);
        // console.log('2e: ', e.target.parentNode.nodeName);
        // console.log('3e: ', e.target.parentNode.parentNode.nodeName);
        if (e.target.parentNode.parentNode.nodeName) {
          // 获取选中的文本
          const selection = iframeDoc.getSelection();
          if (selection.rangeCount > 0) {
            const selectedText = selection.getRangeAt(0).toString();
            if (selectedText.length > 0) {
              // 这里处理选中内容的点击事件
              // console.log('选中的文本:', selectedText);

              let type: number;
              if (e.target.parentNode.parentNode.nodeName === 'BODY' || e.target.parentNode.parentNode.nodeName === 'HTML') {
                type = 1;
              } else {
                type = 2;
              }

              labelType.value = 2;
              labelObj.value = {
                sentence: selectedText,
                type
              };
              openEditLabelModal();
            }
          }
        }
      },
      false
    );
  }

  // 编辑器初始化成功后再获取文档内容
  getHtmlByDocument(props.filePath);
}

const catalogMap: any = {};

// 解析目录树
function analyzeDirectoryTree(section: any) {
  let liItem;
  let completeImg;
  let incompleteImg;
  let titleItem;
  let sectionItem;
  let itemContent;
  let editImg;
  let handleItem;
  let writeImg;
  let deleteImg;
  let addImg;
  let ulList;
  let child;
  let childList;
  if (section.children.length) {
    ulList = document.createElement('ul');
    for (let i: number = 0; i < section.children.length; i++) {
      child = section.children[i];
      // console.log("child.startAddress: ", child)
      // 设置目录节点内容标签(去除前后的空格)
      const title = child.title.trim();
      if (title.length === 0) continue;
      // 已完成
      completeImg = document.createElement('img');
      completeImg.src = CompleteImg;
      completeImg.className = 'statusIcon';
      // 未编写
      incompleteImg = document.createElement('img');
      incompleteImg.src = IncompleteImg;
      incompleteImg.className = 'statusIcon';

      // 目录标题
      sectionItem = document.createElement('span');
      sectionItem.className = 'itemTitle';
      sectionItem.textContent = title;
      editImg = document.createElement('img');
      editImg.src = EditImg;
      editImg.className = 'editIcon';
      titleItem = document.createElement('div');
      titleItem.className = 'titleItem';
      // titleItem.append(completeImg);
      titleItem.append(sectionItem);
      // titleItem.append(editImg);

      writeImg = document.createElement('img');
      writeImg.src = WriteImg;
      writeImg.className = 'writeIcon';
      addImg = document.createElement('img');
      addImg.src = AddImg;
      addImg.className = 'addIcon';
      deleteImg = document.createElement('img');
      deleteImg.src = DeleteImg;
      deleteImg.className = 'deleteIcon';
      handleItem = document.createElement('div');
      handleItem.className = 'handleItem';
      handleItem.append(writeImg);
      handleItem.append(addImg);
      handleItem.append(deleteImg);

      itemContent = document.createElement('div');
      itemContent.className = 'sectionItem';
      itemContent.append(titleItem);
      // itemContent.append(handleItem);
      itemContent.setAttribute('data-address', child.startAddress.join(','));

      catalogMap[child.startAddress.join(',')] = child;
      // 设置目录节点容器标签
      liItem = document.createElement('li');
      liItem.setAttribute('type', child.tag);
      liItem.append(itemContent);
      // 继续遍历子节点
      if (liItem.children.length) {
        childList = analyzeDirectoryTree(child);
        childList && liItem.append(childList);
      }
      ulList.append(liItem);
    }
  }
  return ulList;
}

// 获取文档目录树
function getCatalogHandle() {
  const catalogTree: any = ueditor.value.execCommand('getsections');

  // console.log('目录树：', catalogTree);
  // console.log('目录树：', analyzeDirectoryTree(catalogTree));
  // console.log('目录树catalogMap：', catalogMap);
  const directoryTree = analyzeDirectoryTree(catalogTree);
  // console.log('directoryTree: ', directoryTree);

  if (!directoryTree) return;

  // 更新目录树
  const catalogEle = document.getElementById('catalog_box')!;
  catalogEle.innerHTML = directoryTree?.outerHTML;

  /** 选中章节监听sectionItem的点击事件会让下面其他点击事件优先跳转到对应内容再触发 监听itemTitle的点击事件只会点击章节标题才会跳转 */
  // 选中章节
  const sectionItemEle = document.getElementsByClassName('itemTitle');
  for (let i: number = 0; i < sectionItemEle.length; i++) {
    sectionItemEle[i].addEventListener('click', (e: any) => {
      // console.log("e: ", e, e.target);
      const address = e.target.parentElement.parentElement.getAttribute('data-address');
      ueditor.value.execCommand('selectsection', catalogMap[address], true);
      console.log('catalogMap[address]: ', catalogMap[address]);
      // 清除选区
      ueditor.value.selection.clearRange();
    });
  }
}

// 根据文档获取html内容
function getHtmlByDocument(filePath: string) {
  const { VITE_OTHER_SERVICE_BASE_URL } = import.meta.env;
  const otherUrl = JSON.parse(VITE_OTHER_SERVICE_BASE_URL);
  const docPath: string = otherUrl.fileUrl + filePath;
  loadingDes.value = '文档较大，正在努力处理中，请稍后...';
  showLoading.value = true;
  fetch(docPath, { cache: 'no-cache' })
    .then(response => response.blob())
    .then(blobData => {
      let file: File | null = new File([blobData], `${props.fileName}.docx`, {
        type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        lastModified: Date.now()
      });

      analysisWord(file).then(html => {
        for (let i: number = 0; i < imgList.value.length; i++) {
          docContentHtml.value = docContentHtml.value.replace(IMAGE_TAG, imgList.value[i]);
        }
        docContentHtml.value = docContentHtml.value.replace(/style=""/g, '');
        // 插入文本
        ueditor.value.setContent(docContentHtml.value);
        // 设置内容光标到内容最前面
        ueditor.value.focus();
        getCatalogHandle();
        contentDomOptimize();
        getLabelAction();
        showLoading.value = false;
        // nextTick(() => {
        //   saveContentToService(1);
        // });
      });

      // 文件信息置空
      file = null;
    })
    .catch(error => {
      console.error('发生错误：', error);
      errorMessage('获取文档失败');
      showLoading.value = false;
    });
}

// 获取编辑器iframe元素中的标签内容
function getIframeContent() {
  // 获取编辑器iframe
  const iframe = ueditor.value.iframe;
  const iframeDoc = iframe.contentDocument || iframe.contentWindow.document;

  // 在iframe中查找对应文本
  const walker = document.createTreeWalker(iframeDoc.body, NodeFilter.SHOW_TEXT, null, false);
  return walker.root.childNodes;
}

// 解析word文件，将word转为html
function analysisWord(file: any) {
  return new Promise(resolve => {
    const reader = new FileReader();
    reader.onload = evt => {
      // console.log('evt：', evt);
      // 当文件读取完毕后
      // p标签首行没有缩进
      const options = {
        transformDocument: transformElement,
        styleMap: ["p[style-name='Section Title'] => h1:fresh", "p[style-name='Subsection Title'] => h2:fresh"]
      };

      // 调用mammoth组件的方法进行解析文件
      mammoth
        .convertToHtml({ arrayBuffer: evt.target!.result }, options)
        .then(async resultObject => {
          // console.log("resultObject: ", resultObject);
          const imgSrcReg = /<img[^>]+src=[\\'|\\"]?([^(?"|?'|?>)]+)[\\'|\\"]?[^>]*>/gim;
          const imgSrcList = resultObject.value.match(imgSrcReg);

          for (let i: number = 0; i < imgSrcList?.length; i++) {
            const imgSrc: string = imgSrcList[i].match(/src="(.+?)"/)[1];

            // console.log('imgSrc: ', imgSrc);
            const info = await getImageInfoFromBase64(imgSrc);
            if (info) {
              imgSrcList[i] =
                `${imgSrcList[i].substring(0, imgSrcList[i].length - 2)}width="${info.width}" height="${info.height}" ${imgSrcList[i].substring(imgSrcList[i].length - 2)}`;
            } else {
              imgSrcList[i] =
                `${imgSrcList[i].substring(0, imgSrcList[i].length - 2)}width="90%" height="auto" ${imgSrcList[i].substring(imgSrcList[i].length - 2)}`;
            }
          }

          if (imgSrcList) {
            imgList.value = imgSrcList;
          }

          // console.log('imgList.value: ', imgList.value);
          resolve(resultObject.value); // 将处理好的html数据返回
          reader.abort(); // 关闭读取
        })
        .catch(err => {
          console.log('err: ', err);
          reader.abort(); // 关闭读取
        });
    };
    reader.readAsArrayBuffer(file);
    // 启动读取指定的 Blob 或 File 内容：https://developer.mozilla.org/zh-CN/docs/Web/API/FileReader/readAsArrayBuffer
  });
}

/**
 * transformElement 和 transformParagraph 是用于将文档转换为HTML的。 用于文档转换的API是不稳定的，并且可能在任何版本之间发生变化。
 * 如果你依赖这种行为，你应该固定到mammath.js的特定版本，并在更新前仔细测试。
 */
// 元素重新定义
function transformElement(element: any) {
  if (element.children) {
    const children: any = _.map(element.children, transformElement);
    element = { ...element, children };
  }

  if (element.type === 'paragraph') {
    element = transformParagraph(element);
  }

  if (element.type === 'document') {
    // docParagraphList.value = element.children;
    // console.log('docParagraphList.value: ', element.children);
    htmlFormat(element.children);
  }

  return element;
}

// 段落内容重新定义
function transformParagraph(element: any) {
  if (element.alignment === 'center' && !element.styleId) {
    return { ...element, styleId: 'Heading2' };
  }
  return element;
}

// 根据文档解析API进行HTML内容拼接封装
function htmlFormat(docParagraphList: any[]) {
  let docHtmlStr: string = '';
  for (let i: number = 0; i < docParagraphList.length; i++) {
    const paragraphObj: any = docParagraphList[i];
    if (paragraphObj.type === 'paragraph') {
      // 普通段落内容（包括文字和图片）
      let paragraphStr: string = '';
      let alignmentStr: string = '';
      if (paragraphObj.alignment) {
        alignmentStr = `text-align: ${paragraphObj.alignment}; line-height: 150%; align-items: baseline;`;
      } else {
        alignmentStr = 'text-align: left; line-height: 150%; align-items: baseline;';
      }

      for (let j: number = 0; j < paragraphObj.children.length; j++) {
        if (paragraphObj.indent && paragraphObj.indent.firstLine) {
          alignmentStr += 'text-indent: 2em;';
        }
        const formatContent = paragraphHtmlFormat(paragraphObj.children[j]);
        if (formatContent === IMAGE_TAG) {
          alignmentStr = 'display: block; text-align: center;';
        }
        paragraphStr += formatContent;
      }
      if (paragraphObj.styleId === 'Heading1' || paragraphObj.styleName === 'heading 1') {
        docHtmlStr += `<h1 style="${alignmentStr}">${paragraphStr}</h1>`;
      } else if (paragraphObj.styleId === 'Heading2' || paragraphObj.styleName === 'heading 2') {
        docHtmlStr += `<h2 style="${alignmentStr}">${paragraphStr}</h2>`;
      } else if (paragraphObj.styleId === 'Heading3' || paragraphObj.styleName === 'heading 3') {
        docHtmlStr += `<h3 style="${alignmentStr}">${paragraphStr}</h3>`;
      } else if (paragraphObj.styleId === 'Heading4' || paragraphObj.styleName === 'heading 4') {
        docHtmlStr += `<h4 style="${alignmentStr}">${paragraphStr}</h4>`;
      } else if (paragraphObj.styleId === 'Heading5' || paragraphObj.styleName === 'heading 5') {
        docHtmlStr += `<h5 style="${alignmentStr}">${paragraphStr}</h5>`;
      } else if (paragraphObj.styleId === 'Heading6' || paragraphObj.styleName === 'heading 6') {
        docHtmlStr += `<h6 style="${alignmentStr}">${paragraphStr}</h6>`;
      } else {
        docHtmlStr += `<p style="${alignmentStr}">${paragraphStr}</p>`;
      }
    } else if (paragraphObj.type === 'table') {
      // 表格内容处理
      const tableObj: any = docParagraphList[i];
      docHtmlStr += tableHtmlFormat(tableObj);
    }
  }
  docContentHtml.value = `<div style="margin: 72pt;">${docHtmlStr}</div>`;
}

// 段落内容格式化
function paragraphHtmlFormat(paragraphObj: any) {
  let contentStr: string = '';

  // console.log("paragraphObj: ", paragraphObj);

  if (!paragraphObj.children) {
    return '<span></span>';
  }

  if (paragraphObj.children.length === 0) {
    return '<br/>';
  }

  for (let i: number = 0; i < paragraphObj.children.length; i++) {
    if (paragraphObj.children[i].type === 'text') {
      let textStr: string = paragraphObj.children[i].value;
      // 如果有html字符串，将其解析为html字符串，就可以正常展示
      textStr = escapeHTMLManually(textStr);

      let styleStr: string = `line-height: 150%;`;
      if (paragraphObj.font) {
        styleStr += `font-family: ${paragraphObj.font};`;
      }
      if (paragraphObj.fontSize) {
        styleStr += `font-size: ${paragraphObj.fontSize}pt;`;
      }
      // 是否有下划线
      if (paragraphObj.isUnderline) {
        styleStr += 'text-decoration: underline;';
      }
      // 是否有删除线
      if (paragraphObj.isStrikethrough) {
        styleStr += 'text-decoration: line-through;';
      }
      // if (paragraphObj.verticalAlignment) {
      //   styleStr += `display: block; align-items: ${paragraphObj.verticalAlignment};`;
      // }
      // 是否加粗(使用 strong 标签加粗内容)
      if (paragraphObj.isBold) {
        styleStr += 'font-weight: bold;';
      }
      contentStr += `<span style="${styleStr}">${textStr}</span>`;
    } else if (paragraphObj.children[i].type === 'break') {
      // 换行
      contentStr += '<br/>';
    } else if (paragraphObj.children[i].type === 'image') {
      // 图片
      contentStr += IMAGE_TAG;
    } else {
      contentStr = String(contentStr);
    }
  }

  // return `<span><span>${contentStr}</span></span>`;
  return contentStr;
}

// 表格内容格式化
function tableHtmlFormat(tableObj: any) {
  let tableStr: string = '';
  const tableStyle: string = '';
  for (let i: number = 0; i < tableObj.children.length; i++) {
    // 遍历 tableRow
    const rowObj: any = tableObj.children[i];
    if (rowObj.isHeader) {
      tableStr += '<thead><tr>';
    } else {
      tableStr += '<tbody><tr>';
    }
    for (let j: number = 0; j < rowObj.children.length; j++) {
      // 遍历 tableCell
      const cellObj: any = rowObj.children[j];
      if (rowObj.isHeader) {
        tableStr += `<th style="${tableStyle}">`;
      } else {
        tableStr += `<td>`;
      }
      for (let k: number = 0; k < cellObj.children.length; k++) {
        const contentObj: any = cellObj.children[k];

        let paragraphStr: string = '';
        let alignmentStr: string = '';
        if (contentObj.alignment) {
          alignmentStr = `text-align: ${contentObj.alignment};`;
        } else {
          alignmentStr = 'text-align: left;';
        }
        for (let l: number = 0; l < contentObj.children.length; l++) {
          if (contentObj.children.length > 1 && l === 0 && contentObj.indent && contentObj.indent.firstLine) {
            alignmentStr += 'text-indent: 2em;';
          }
          paragraphStr += paragraphHtmlFormat(contentObj.children[l]);
        }
        tableStr += `<p style="${alignmentStr}">${paragraphStr}</p>`;
      }
      if (rowObj.isHeader) {
        tableStr += '</th>';
      } else {
        tableStr += '</td>';
      }
    }
    if (rowObj.isHeader) {
      tableStr += '</tr></thead>';
    } else {
      tableStr += '</tr></tbody>';
    }
  }
  return `<table style="width: 100%; border-collapse: collapse;">${tableStr}</table>`;
}

const hTagList: string[] = ['H1', 'H2', 'H3', 'H4', 'H5', 'H6'];

// 获取文档标签
async function getLabelAction() {
  const walkerNodes: any[] = getIframeContent();

  for (let i: number = 0; i < props.labelList.length; i++) {
    const item: any = props.labelList[i];
    for (let j: number = 0; j < walkerNodes.length; j++) {
      const childNode: any = walkerNodes[j];
      if (childNode.nodeName === 'P' || hTagList.includes(childNode.nodeName)) {
        pLabelNodeContentFormat(item, childNode);
      } else if (childNode.nodeName === 'TABLE') {
        if (childNode.textContent.includes(item.sentence)) {
          for (let k: number = 0; k < childNode.children.length; k++) {
            const tableRow: any = childNode.children[k]; // TBODY
            for (let l: number = 0; l < tableRow.children.length; l++) {
              const tableCell: any = tableRow.children[l]; // TR
              for (let m: number = 0; m < tableCell.children.length; m++) {
                const tdContent: any = tableCell.children[m]; // TD
                for (let n: number = 0; n < tdContent.children.length; n++) {
                  const cellContent: any = tdContent.children[n];
                  if (cellContent.nodeName === 'P' || hTagList.includes(cellContent.nodeName)) {
                    pLabelNodeContentFormat(item, cellContent);
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}

let nodeIndex: number = 0;

// P标签内容优化
function pLabelNodeContentFormat(item: any, childNode: any) {
  if (childNode.textContent.length >= item.sentence.length) {
    if (childNode.textContent.includes(item.sentence)) {
      const labelTextContent: string = childNode.textContent;
      let childNodeStyle: string = '';

      if (childNode && childNode.children && childNode.children.length > 0) {
        if (childNode.children.length === 1) {
          const childrenNodeStyle = childNode.children[0].getAttribute('style');

          childNodeStyle = contentColorHandle(item.color, childrenNodeStyle);

          const startIndex: number = labelTextContent.indexOf(item.sentence);
          const endIndex: number = startIndex + item.sentence.length;

          const startNode: any = document.createElement('span');
          startNode.textContent = labelTextContent.substring(0, startIndex);
          startNode.setAttribute('style', childrenNodeStyle);
          if (startNode.textContent.length > 0) {
            childNode.appendChild(startNode);
          }

          const centerNode: any = document.createElement('span');
          if (childNodeStyle !== '') {
            centerNode.setAttribute('style', childNodeStyle);
          }
          centerNode.textContent = labelTextContent.substring(startIndex, endIndex);
          childNode.appendChild(centerNode);

          const endNode: any = document.createElement('span');
          endNode.textContent = labelTextContent.substring(endIndex);
          endNode.setAttribute('style', childrenNodeStyle);
          if (endNode.textContent.length > 0) {
            childNode.appendChild(endNode);
          }

          childNode.removeChild(childNode.children[0]);
        } else {
          // TODO 增加递归使整个节点内容都被处理
          nodeIndex = 0;
          multiContentNodeFormat(item, childNode, nodeIndex);
        }
      }
    }
  } else if (item.sentence.includes(childNode.textContent)) {
    // const labelTextContent: string = childNode.textContent;
    // if (labelTextContent === '') return;
    // nodeIndex = 0;
    // multiContentNodeFormat(item, childNode, nodeIndex);
  }
}

// 多片段内容处理
function multiContentNodeFormat(item: any, childNode: any, index: number) {
  if (index >= childNode.children.length) return;

  let targetNode: any = null;
  const spanChildNode = childNode.children[index];
  if (spanChildNode.nodeName === 'SPAN') {
    const spanChildText: string = trimPunctuation(spanChildNode.textContent);
    if (item.sentence.length >= spanChildText.length) {
      if (item.sentence.includes(spanChildText)) {
        targetNode = spanChildNode;
      }
    } else if (spanChildText.includes(item.sentence)) {
      targetNode = spanChildNode;
    }

    if (targetNode) {
      const targetText: string = targetNode.textContent;
      const targetNodeStyle: string = targetNode.getAttribute('style');

      const spanNodeStyle: string = contentColorHandle(item.color, targetNodeStyle);

      const targetContentText: string = trimPunctuation(targetText);

      if (item.sentence.length >= targetContentText.length) {
        const centerSpanNode: any = document.createElement('span');
        if (spanNodeStyle !== '') {
          centerSpanNode.setAttribute('style', spanNodeStyle);
        }
        centerSpanNode.textContent = targetText;
        childNode.replaceChild(centerSpanNode, targetNode);
      } else {
        const startIndex: number = targetText.indexOf(item.sentence);
        const endIndex: number = startIndex + item.sentence.length;

        const endSpanNode: any = document.createElement('span');
        endSpanNode.textContent = targetText.substring(endIndex);
        endSpanNode.setAttribute('style', targetNodeStyle);
        if (endSpanNode.textContent.length > 0) {
          childNode.insertBefore(endSpanNode, targetNode);
        }

        const centerSpanNode: any = document.createElement('span');
        if (spanNodeStyle !== '') {
          centerSpanNode.setAttribute('style', spanNodeStyle);
        }
        centerSpanNode.textContent = targetText.substring(startIndex, endIndex);
        if (endSpanNode.textContent.length > 0) {
          childNode.insertBefore(centerSpanNode, endSpanNode);
        } else {
          childNode.insertBefore(centerSpanNode, targetNode);
        }

        const startSpanNode: any = document.createElement('span');
        startSpanNode.textContent = targetText.substring(0, startIndex);
        startSpanNode.setAttribute('style', targetNodeStyle);
        if (startIndex > 0) {
          childNode.insertBefore(startSpanNode, centerSpanNode);
        }

        childNode.removeChild(targetNode);

        // multiContentNodeFormat(item, childNode, nodeIndex);
      }
      nodeIndex += 1;
      multiContentNodeFormat(item, childNode, nodeIndex);
    } else {
      nodeIndex += 1;
      multiContentNodeFormat(item, childNode, nodeIndex);
    }
  } else {
    nodeIndex += 1;
    multiContentNodeFormat(item, childNode, nodeIndex);
  }
}

// 去除字符串中的标点符号
function trimPunctuation(str: string) {
  return str.replace(/^[\p{P}\p{S}\s]+|[\p{P}\p{S}\s]+$/gu, '');
}

const bgColorList: string[] = [
  'background-color: #FCF3E8;',
  'background-color: #EFD0CD;',
  'background-color: #CCD5F6;',
  'background-color: #F0F6E7;',
  'background-color: #EEE5FE;'
];

// 内容颜色处理
function contentColorHandle(color: number, nodeStyle: string) {
  let spanNodeStyle: string = '';
  for (let i: number = 0; i < bgColorList.length; i++) {
    if (nodeStyle.includes(bgColorList[i])) {
      spanNodeStyle = nodeStyle.replace(bgColorList[i], '');
    }
  }

  switch (color) {
    case 1:
      spanNodeStyle = `${nodeStyle}background-color: #FCF3E8;`;
      break;
    case 2:
      spanNodeStyle = `${nodeStyle}background-color: #EFD0CD;`;
      break;
    case 3:
      spanNodeStyle = `${nodeStyle}background-color: #CCD5F6;`;
      break;
    case 4:
      spanNodeStyle = `${nodeStyle}background-color: #F0F6E7;`;
      break;
    case 5:
      spanNodeStyle = `${nodeStyle}background-color: #EEE5FE;`;
      break;
    default:
      spanNodeStyle = '';
  }
  return spanNodeStyle;
}

// 内容Dom节点优化
function contentDomOptimize() {
  const walkerNodes: any[] = getIframeContent();

  for (let i: number = 0; i < walkerNodes.length; i++) {
    const node = walkerNodes[i];
    if (node.nodeName === 'P' || hTagList.includes(node.nodeName)) {
      spanDomOptimize(node);
    } else if (node.nodeName === 'TABLE') {
      // 表格
      const tableChildNode: any = node.childNodes;
      for (let j: number = 0; j < tableChildNode.length; j++) {
        const childNode: any = tableChildNode[j];
        if (childNode.nodeName === 'TR') {
          const trChildNode: any = childNode.childNodes;
          for (let k: number = 0; k < trChildNode.length; k++) {
            const tdNode: any = trChildNode[k];
            if (tdNode.nodeName === 'TD' || tdNode.nodeName === 'TH') {
              const tdChildNode: any = tdNode.childNodes;
              for (let m: number = 0; m < tdChildNode.length; m++) {
                const childNode: any = tdChildNode[m];
                if (childNode.nodeName === 'P' || hTagList.includes(childNode.nodeName)) {
                  spanDomOptimize(childNode);
                }
              }
            }
          }
        }
      }
    }
  }
}

// Span标签内容优化
function spanDomOptimize(node: any) {
  const textContent: string = node.textContent;
  let childNodeStyle: string = '';
  const childStyle: string[] = [];
  for (let j: number = 0; j < node.children.length; j++) {
    const childNode: any = node.children[j];
    if (childNode.getAttribute('style')) {
      childStyle.push(childNode.getAttribute('style'));
    } else {
      childStyle.push('');
    }
  }
  const newChildStyle: string[] = Array.from(new Set(childStyle));
  if (newChildStyle.length > 0) {
    if (newChildStyle.length === 1) {
      childNodeStyle = newChildStyle[0];

      while (node.firstChild && node.firstChild.nodeName === 'SPAN') {
        node.removeChild(node.firstChild);
      }

      const spanNode: any = document.createElement('span');
      spanNode.setAttribute('style', childNodeStyle);
      spanNode.textContent = textContent;
      node.append(spanNode);
    } else {
      // Warning: 暂不支持多样式合并
    }
  } else {
    while (node.firstChild && node.firstChild.nodeName === 'SPAN') {
      node.removeChild(node.firstChild);
    }

    const spanNode: any = document.createElement('span');
    spanNode.textContent = textContent;
    node.append(spanNode);
  }
}

const chapterStatus = ref<boolean>(true);

// 章节状态改变
function chapterStatusChangeClick() {
  chapterStatus.value = !chapterStatus.value;
}

const currentLabelItemIndex = ref<number | undefined>(undefined);
const borderStyle = ref<string>('border: 2px solid red; padding: 5px;');

// 查询并定位标签对应的正文位置
function searchAndLocateLabel(event: any, item: any, index: number) {
  // 清除选区
  ueditor.value.selection.clearRange();

  if (index === currentLabelItemIndex.value) return;
  currentLabelItemIndex.value = index;

  // console.log(item);
  const content = ueditor.value.getContentTxt();
  const startIndex = content.indexOf(item.sentence);

  if (startIndex !== -1) {
    const walkerNodes: any[] = getIframeContent();

    let node;
    let offsetTop: number = 0;
    for (let j: number = 0; j < walkerNodes.length; j++) {
      const childNode: any = walkerNodes[j];
      if ((childNode.nodeName === 'P' || hTagList.includes(childNode.nodeName)) && item.type === 1) {
        if (childNode.textContent && childNode.textContent.includes(item.sentence)) {
          node = childNode;
          offsetTop = node.offsetTop;
          break;
        }
      } else if (childNode.nodeName === 'TABLE' && item.type === 2) {
        try {
          if (childNode.textContent && childNode.textContent.includes(item.sentence)) {
            for (let k: number = 0; k < childNode.children.length; k++) {
              const tableRow: any = childNode.children[k]; // TBODY
              for (let l: number = 0; l < tableRow.children.length; l++) {
                const tableCell: any = tableRow.children[l]; // TR
                for (let m: number = 0; m < tableCell.children.length; m++) {
                  const tdContent: any = tableCell.children[m]; // TD
                  for (let n: number = 0; n < tdContent.children.length; n++) {
                    const cellContent: any = tdContent.children[n];
                    if (cellContent.nodeName === 'P' || hTagList.includes(cellContent.nodeName)) {
                      if (cellContent.textContent && cellContent.textContent.includes(item.sentence)) {
                        const position = getElementPosition(tableCell, childNode);
                        // console.log('position: ', position);
                        // console.log('table_offsetTop: ', childNode.offsetTop, cellContent.offsetTop);
                        // 抛出异常的方式中断整个嵌套循环
                        throw {
                          name: 'searchResult',
                          node: cellContent,
                          offsetTop: childNode.offsetTop + position.top
                        };
                      }
                    }
                  }
                }
              }
            }
          }
        } catch (error: any) {
          console.log('error: ', error);
          if (error.name === 'searchResult') {
            node = error.node;
            offsetTop = error.offsetTop;
            break;
          }
        }
      }
    }

    // console.log('searchText: ', searchText);

    if (node) {
      removeBorderStyle(walkerNodes);

      let nodeStyle: any = node.getAttribute('style');
      // console.log('nodeStyle: ', nodeStyle);
      if (!nodeStyle.includes(borderStyle)) {
        nodeStyle += borderStyle.value;
      }
      node.setAttribute('style', nodeStyle);

      const range = document.createRange();
      range.setStart(node, 0);
      range.setEnd(node, node.childNodes.length);

      // 获取编辑器iframe
      const iframe = ueditor.value.iframe;
      // iframe.contentWindow.innerHeight / 2.0
      iframe.contentWindow.scrollTo(0, offsetTop - 100);
    }
  } else {
    console.log('未找到指定内容');
  }
}

// 搜索并定位（查找）
function searchAndLocateSentenceClick(item: any) {
  // console.log(item);
  const content = ueditor.value.getContentTxt();
  const startIndex = content.indexOf(item.sentence);

  if (startIndex !== -1) {
    const walkerNodes: any[] = getIframeContent();

    let node;
    let offsetTop: number = 0;
    for (let j: number = 0; j < walkerNodes.length; j++) {
      const childNode: any = walkerNodes[j];
      if ((childNode.nodeName === 'P' || hTagList.includes(childNode.nodeName)) && item.type === 1) {
        if (childNode.textContent && childNode.textContent.includes(item.sentence)) {
          node = childNode;
          offsetTop = node.offsetTop;
          break;
        }
      } else if (childNode.nodeName === 'TABLE' && item.type === 2) {
        try {
          if (childNode.textContent && childNode.textContent.includes(item.sentence)) {
            for (let k: number = 0; k < childNode.children.length; k++) {
              const tableRow: any = childNode.children[k]; // TBODY
              for (let l: number = 0; l < tableRow.children.length; l++) {
                const tableCell: any = tableRow.children[l]; // TR
                for (let m: number = 0; m < tableCell.children.length; m++) {
                  const tdContent: any = tableCell.children[m]; // TD
                  for (let n: number = 0; n < tdContent.children.length; n++) {
                    const cellContent: any = tdContent.children[n];
                    if (cellContent.nodeName === 'P' || hTagList.includes(cellContent.nodeName)) {
                      if (cellContent.textContent && cellContent.textContent.includes(item.sentence)) {
                        const position = getElementPosition(tableCell, childNode);
                        // 抛出异常的方式中断整个嵌套循环
                        throw {
                          name: 'searchResult',
                          node: cellContent,
                          offsetTop: childNode.offsetTop + position.top
                        };
                      }
                    }
                  }
                }
              }
            }
          }
        } catch (error: any) {
          if (error.name === 'searchResult') {
            node = error.node;
            offsetTop = error.offsetTop;
            break;
          }
        }
      }
    }

    if (node) {
      // 获取编辑器iframe
      const iframe = ueditor.value.iframe;
      // iframe.contentWindow.innerHeight / 2.0
      iframe.contentWindow.scrollTo(0, offsetTop - 100);
    }
  } else {
    console.log('未找到指定内容');
  }
}

// 获取表格元素在表格中的相对位置
function getElementPosition(element: any, table: any) {
  let top = element.offsetTop;
  let left = element.offsetLeft;
  let parent = element.offsetParent;

  while (parent && parent !== table) {
    top += parent.offsetTop;
    left += parent.offsetLeft;
    parent = parent.offsetParent;
  }

  return { top, left };
}

// 移除标签的边框标记样式
function removeBorderStyle(walkerChildNodes: any) {
  for (let j: number = 0; j < walkerChildNodes.length; j++) {
    const childNode: any = walkerChildNodes[j];
    if ((childNode.nodeName === 'P' || hTagList.includes(childNode.nodeName))) {
      let nodeStyle = childNode.getAttribute('style');
      if (nodeStyle && nodeStyle.includes(borderStyle.value)) {
        nodeStyle = nodeStyle.replace(borderStyle.value, '');
        childNode.setAttribute('style', nodeStyle);
      }
    } else if (childNode.nodeName === 'TABLE') {
      for (let k: number = 0; k < childNode.children.length; k++) {
        const tableRow: any = childNode.children[k]; // TBODY
        for (let l: number = 0; l < tableRow.children.length; l++) {
          const tableCell: any = tableRow.children[l]; // TR
          for (let m: number = 0; m < tableCell.children.length; m++) {
            const tdContent: any = tableCell.children[m]; // TD
            for (let n: number = 0; n < tdContent.children.length; n++) {
              const cellContent: any = tdContent.children[n];
              if (cellContent.nodeName === 'P' || hTagList.includes(cellContent.nodeName)) {
                let nodeStyle = cellContent.getAttribute('style');
                if (nodeStyle && nodeStyle.includes(borderStyle.value)) {
                  nodeStyle = nodeStyle.replace(borderStyle.value, '');
                  cellContent.setAttribute('style', nodeStyle);
                }
              }
            }
          }
        }
      }
    }
  }
}

const dialog = useDialog();

// 删除标签
function deleteLabelClick(item: any, labelItem: any) {
  dialog.warning({
    title: '温馨提示',
    content: '小主，删除后将无法找回，您是否删除?',
    positiveText: '确认',
    negativeText: '取消',
    onPositiveClick() {
      deleteLabelHandle(item, labelItem);
    }
  });
}

// 删除标签确认
async function deleteLabelHandle(item: any, labelItem: any) {
  const params: any = {
    logId: props.logId,
    ids: labelItem.id
  };
  const { data, error } = await labelBindingDeleteAction(params);
  if (!error) {
    successMessage('标签删除成功');
    emit('refresh');

    const labelBindings: any = item.labelBindings.filter((label: any) => label.id !== labelItem.id);
    if (labelBindings.length === 0) {
      // 1.清除选中边框
      removeBorderStyle(getIframeContent());

      // 2.清除选中文本的样式
      clearSelectedTextStyle(item);
    }
  }
}

// 清除选中文本的样式
function clearSelectedTextStyle(item: any) {
  const walkerNodes: any[] = getIframeContent();

  for (let j: number = 0; j < walkerNodes.length; j++) {
    const childNode: any = walkerNodes[j];
    if (childNode.nodeName === 'P' || hTagList.includes(childNode.nodeName)) {
      clearLabelNodeContentFormat(item, childNode);
    } else if (childNode.nodeName === 'TABLE') {
      if (childNode.textContent.includes(item.sentence)) {
        for (let k: number = 0; k < childNode.children.length; k++) {
          const tableRow: any = childNode.children[k]; // TBODY
          for (let l: number = 0; l < tableRow.children.length; l++) {
            const tableCell: any = tableRow.children[l]; // TR
            for (let m: number = 0; m < tableCell.children.length; m++) {
              const tdContent: any = tableCell.children[m]; // TD
              for (let n: number = 0; n < tdContent.children.length; n++) {
                const cellContent: any = tdContent.children[n];
                if (cellContent.nodeName === 'P' || hTagList.includes(cellContent.nodeName)) {
                  clearLabelNodeContentFormat(item, cellContent);
                }
              }
            }
          }
        }
      }
    }
  }
}

let clearNodeIndex: number = 0;

// 清除P标签内容文本的颜色标记
function clearLabelNodeContentFormat(item: any, childNode: any) {
  if (childNode.textContent.length >= item.sentence.length) {
    if (childNode.textContent.includes(item.sentence)) {
      const labelTextContent: string = childNode.textContent;
      let childNodeStyle: string = '';

      if (childNode && childNode.children && childNode.children.length > 0) {
        if (childNode.children.length === 1) {
          const childrenNodeStyle = childNode.children[0].getAttribute('style');

          childNodeStyle = clearContentColorHandle(childrenNodeStyle);

          const startIndex: number = labelTextContent.indexOf(item.sentence);
          const endIndex: number = startIndex + item.sentence.length;

          const startNode: any = document.createElement('span');
          startNode.textContent = labelTextContent.substring(0, startIndex);
          startNode.setAttribute('style', childrenNodeStyle);
          if (startNode.textContent.length > 0) {
            childNode.appendChild(startNode);
          }

          const centerNode: any = document.createElement('span');
          if (childNodeStyle !== '') {
            centerNode.setAttribute('style', childNodeStyle);
          }
          centerNode.textContent = labelTextContent.substring(startIndex, endIndex);
          childNode.appendChild(centerNode);

          const endNode: any = document.createElement('span');
          endNode.textContent = labelTextContent.substring(endIndex);
          endNode.setAttribute('style', childrenNodeStyle);
          if (endNode.textContent.length > 0) {
            childNode.appendChild(endNode);
          }

          childNode.removeChild(childNode.children[0]);
        } else {
          // TODO 增加递归使整个节点内容都被处理
          clearNodeIndex = 0;
          clearMultiContentNodeFormat(item, childNode, nodeIndex);
        }
      }
    }
  } else if (item.sentence.includes(childNode.textContent)) {
    // const labelTextContent: string = childNode.textContent;
    // if (labelTextContent === '') return;
    // nodeIndex = 0;
    // multiContentNodeFormat(item, childNode, nodeIndex);
  }
}

// 多片段内容处理
function clearMultiContentNodeFormat(item: any, childNode: any, index: number) {
  if (index >= childNode.children.length) return;

  let targetNode: any = null;
  const spanChildNode = childNode.children[index];
  if (spanChildNode.nodeName === 'SPAN') {
    const spanChildText: string = trimPunctuation(spanChildNode.textContent);
    if (item.sentence.length >= spanChildText.length) {
      if (item.sentence.includes(spanChildText)) {
        targetNode = spanChildNode;
      }
    } else if (spanChildText.includes(item.sentence)) {
      targetNode = spanChildNode;
    }

    if (targetNode) {
      const targetText: string = targetNode.textContent;
      const targetNodeStyle: string = targetNode.getAttribute('style');

      const spanNodeStyle: string = clearContentColorHandle(targetNodeStyle);

      const targetContentText: string = trimPunctuation(targetText);

      if (item.sentence.length >= targetContentText.length) {
        const centerSpanNode: any = document.createElement('span');
        if (spanNodeStyle !== '') {
          centerSpanNode.setAttribute('style', spanNodeStyle);
        }
        centerSpanNode.textContent = targetText;
        childNode.replaceChild(centerSpanNode, targetNode);
      } else {
        const startIndex: number = targetText.indexOf(item.sentence);
        const endIndex: number = startIndex + item.sentence.length;

        const endSpanNode: any = document.createElement('span');
        endSpanNode.textContent = targetText.substring(endIndex);
        endSpanNode.setAttribute('style', targetNodeStyle);
        if (endSpanNode.textContent.length > 0) {
          childNode.insertBefore(endSpanNode, targetNode);
        }

        const centerSpanNode: any = document.createElement('span');
        if (spanNodeStyle !== '') {
          centerSpanNode.setAttribute('style', spanNodeStyle);
        }
        centerSpanNode.textContent = targetText.substring(startIndex, endIndex);
        if (endSpanNode.textContent.length > 0) {
          childNode.insertBefore(centerSpanNode, endSpanNode);
        } else {
          childNode.insertBefore(centerSpanNode, targetNode);
        }

        const startSpanNode: any = document.createElement('span');
        startSpanNode.textContent = targetText.substring(0, startIndex);
        startSpanNode.setAttribute('style', targetNodeStyle);
        if (startIndex > 0) {
          childNode.insertBefore(startSpanNode, centerSpanNode);
        }

        childNode.removeChild(targetNode);

        // multiContentNodeFormat(item, childNode, nodeIndex);
      }
      clearNodeIndex += 1;
      clearMultiContentNodeFormat(item, childNode, clearNodeIndex);
    } else {
      clearNodeIndex += 1;
      clearMultiContentNodeFormat(item, childNode, clearNodeIndex);
    }
  } else {
    clearNodeIndex += 1;
    clearMultiContentNodeFormat(item, childNode, clearNodeIndex);
  }
}

// 清除内容颜色处理
function clearContentColorHandle(nodeStyle: string) {
  let spanNodeStyle: string = '';
  for (let i: number = 0; i < bgColorList.length; i++) {
    if (nodeStyle.includes(bgColorList[i])) {
      spanNodeStyle = nodeStyle.replace(bgColorList[i], '');
    }
  }

  return spanNodeStyle;
}

const analysisId = ref<number>(0);

// 编辑、新增标签
function addOrEditLabelClick(id: number, item: any, type: number) {
  labelType.value = type;
  analysisId.value = id;
  // 编辑
  if (type === 0) {
    labelObj.value = item;
  }
  openEditLabelModal();
}

// 更新标签数据
function refreshLabelDataAction() {
  emit('refresh');
}

const selectedFilter = ref<number>();
const filterList = ref<any[]>([
  {
    label: '自动生成',
    value: 1,
    bgColor: '#FCF3E8',
    checkName: 'check-label-one'
  },
  {
    label: '废标项',
    value: 2,
    bgColor: '#F6E2E0',
    checkName: 'check-label-two'
  },
  {
    label: '评分项',
    value: 3,
    bgColor: '#E0E6FA',
    checkName: 'check-label-three'
  },
  {
    label: '手动修改',
    value: 4,
    bgColor: '#F0F6E7',
    checkName: 'check-label-four'
  },
  {
    label: '手动添加',
    value: 5,
    bgColor: '#EEE5FE',
    checkName: 'check-label-five'
  }
]);

const searchStatus = ref<boolean>(true);

// 搜索状态改变
function searchStatusChangeClick() {
  searchStatus.value = !searchStatus.value;
}

const filterLabelList = ref<any[]>([]);

// 筛选条件改变
function filterChangeHandle(value: string | number) {
  filterLabelList.value = [];
  for (let i: number = 0; i < props.labelList.length; i++) {
    const labelObj: any = props.labelList[i];
    if (selectedFilter.value.includes(labelObj.color)) {
      filterLabelList.value.push(labelObj);
    }
  }
}

onUnmounted(() => {
  // setTimeout(() => {
  //   if (ueditor.value) {
  //     contentHtml.value = '';
  //     ueditor.value.destroy();
  //     ueditor.value = null;
  //   }
  // }, 100);
});
</script>

<!-- 原文注释 -->
<template>
  <div>
    <NSpin :show="showLoading" :description="loadingDes" :rotate="false" size="large">
      <template #icon>
        <img src="@/assets/imgs/spin-loading.gif" alt="" width="240" height="240" />
      </template>
      <NSpace class="w-full" justify="end">
        <NButton class="top-btn" quaternary @click="chapterStatusChangeClick">
          <template #icon>
            <img v-if="chapterStatus" src="@/assets/smart-eye/icon-close-chapter.png" width="20" alt="" />
            <img v-else src="@/assets/smart-eye/icon-open-chapter.png" width="20" alt="" />
          </template>
          {{ chapterStatus ? '取消章节' : '展开章节' }}
        </NButton>
        <NButton class="top-btn" quaternary @click="searchStatusChangeClick">
          <template #icon>
            <img v-if="searchStatus" src="@/assets/smart-eye/icon-search.png" width="20" alt="" />
            <img v-else src="@/assets/smart-eye/icon-close-search.png" width="20" alt="" />
          </template>
          {{ searchStatus ? '进行查找' : '关闭查找' }}
        </NButton>
      </NSpace>
      <div class="mt-20px flex">
        <div v-show="chapterStatus" class="catalog">
          <div id="catalog_wrapper">
            <div class="top_title_box">
              <img class="ml-5px" src="@/assets/smart-eye/icon-chapter.png" alt="" width="20" height="20" />
              <span class="catalog_title">章节名称</span>
            </div>
            <NScrollbar content-class="catalog-list" class="max-h-580px">
              <div id="catalog_box" class="catalog-list"></div>
            </NScrollbar>
          </div>
        </div>
        <div v-if="isBack" class="z-1200 h-full w-full bg-white"></div>
        <div v-else class="content-box">
          <VueUeditorWrap
            v-model="contentHtml"
            editor-id="label_editor"
            :config="editorConfig"
            :editor-dependencies="editorDependencies"
            @ready="readyHandle"
          />
        </div>
        <div class="label-box">
          <div class="top_title_box">
            <img class="ml-5px" src="@/assets/smart-eye/icon-label-note.png" alt="" width="20" height="20" />
            <span class="catalog_title">标签批注</span>
          </div>
          <NScrollbar v-if="labelList.length > 0" class="max-h-580px">
            <div
              v-for="(item, index) in labelList"
              :key="item.id"
              class="label-item-box"
              :style="{
                padding: analysisType !== 1 && item.labelBindings.length === 0 ? 0 : '7px',
                'border-bottom': analysisType !== 1 && item.labelBindings.length === 0 ? 'none' : '1px dashed #ccc'
              }"
              @click="searchAndLocateLabel($event, item, index)"
            >
              <div class="label-box-item" :style="{ border: currentLabelItemIndex === index ? '2px solid red' : '' }">
                <div
                  v-for="labelItem in item.labelBindings"
                  :key="labelItem.id"
                  class="label-item"
                  :style="{
                    'background-color':
                      item.color === 1
                        ? '#fcf2e8'
                        : item.color === 2
                          ? '#f4e3e0'
                          : item.color === 3
                            ? '#e0e5fb'
                            : item.color === 4
                              ? '#F0F6E7'
                              : '#EEE5FE'
                  }"
                >
                  <span
                    class="label-text"
                    :style="{
                      color:
                        item.color === 1
                          ? '#E99D42'
                          : item.color === 2
                            ? '#BD3124'
                            : item.color === 3
                              ? '#022FD3'
                              : item.color === 4
                                ? '#81B337'
                                : '#7829F5'
                    }"
                  >
                    {{ labelItem.labelName }}
                  </span>
                  <img
                    v-if="analysisType === 1"
                    class="label-img"
                    :src="
                      item.color === 1
                        ? DeleteLabel01Img
                        : item.color === 2
                          ? DeleteLabel02Img
                          : item.color === 3
                            ? DeleteLabel03Img
                            : item.color === 4
                              ? DeleteLabel04Img
                              : DeleteLabel05Img
                    "
                    alt="删除"
                    @click="deleteLabelClick(item, labelItem)"
                  />
                  <img
                    v-if="analysisType === 1"
                    class="label-img"
                    :src="
                      item.color === 1
                        ? EditLabel01Img
                        : item.color === 2
                          ? EditLabel02Img
                          : item.color === 3
                            ? EditLabel03Img
                            : item.color === 4
                              ? EditLabel04Img
                              : EditLabel05Img
                    "
                    alt="编辑"
                    @click="addOrEditLabelClick(item.id, labelItem, 0)"
                  />
                </div>
                <img
                  v-if="analysisType === 1"
                  class="label-add-img"
                  src="@/assets/smart-eye/icon-add-tag.png"
                  alt=""
                  @click="addOrEditLabelClick(item.id, item, 1)"
                />
              </div>
            </div>
          </NScrollbar>
          <NEmpty v-else class="mt-100px" description="暂无标签内容" />
        </div>
        <div v-show="!searchStatus" class="search-box">
          <div class="top_title_box">
            <img class="ml-5px" src="@/assets/smart-eye/icon-search.png" alt="" width="20" height="20" />
            <span class="catalog_title">查找</span>
          </div>
          <div>
            <div class="tag-box">
              <div class="tag-line"></div>
              <span class="tag-text">按照标签颜色筛选</span>
            </div>
            <div>
              <NCheckboxGroup v-model:value="selectedFilter" @update:value="filterChangeHandle">
                <NSpace>
                  <div
                    v-for="item in filterList"
                    :key="item.value"
                    class="filter-box"
                    :style="{
                      'background-color': item.bgColor
                    }"
                  >
                    <NCheckbox :value="item.value" :label="item.label" :class="item.checkName" />
                  </div>
                </NSpace>
              </NCheckboxGroup>
            </div>
          </div>
          <div>
            <div class="tag-box">
              <div class="tag-line"></div>
              <span class="tag-text">查询结果</span>
            </div>
            <NScrollbar v-if="filterLabelList.length > 0" class="max-h-415px">
              <div
                v-for="item in filterLabelList"
                :key="item.id"
                class="sentence-item"
                @click="searchAndLocateSentenceClick(item)"
              >{{ item.sentence }}</div>
            </NScrollbar>
            <NEmpty v-else class="mt-100px" description="暂无查询结果" />
          </div>
        </div>
      </div>
    </NSpin>
    <EditLabel
      v-model:show="showEditLabelModal"
      :analysis-id="analysisId"
      :log-id="logId"
      :type="labelType"
      :label-obj="labelObj"
      @refresh="refreshLabelDataAction"
    />
  </div>
</template>

<style>
#catalog_box li {
  color: #333;
  margin: 10px 0 0;
  cursor: pointer;
  word-break: break-all;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}
#catalog_box li[type='H1'] {
  font-size: 16px;
  font-weight: bold;
}
#catalog_box li[type='H2'] {
  font-weight: bold;
}
#catalog_box li[type='H2'] span {
  font-size: 14px;
  padding-left: 10px;
}
#catalog_box li[type='H3'] span {
  font-size: 12px;
  padding-left: 20px;
}
#catalog_box li[type='H4'] {
  font-size: 10px;
  padding-left: 30px;
}
#catalog_box li[type='H5'] {
  font-size: 10px;
  padding-left: 40px;
}
#catalog_box li[type='H6'] {
  font-size: 10px;
  padding-left: 50px;
}

.titleItem {
  display: flex;
  flex-direction: row;
  align-items: center;
  cursor: pointer;
}
.statusIcon {
  width: 15px;
  margin-right: 2px;
  height: 15px;
}
.sectionItem {
  height: 20px;
  padding: 4px;
  cursor: pointer;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
}

.sectionItem span {
  display: inline-block;
}
.itemTitle {
  max-width: 280px;
  word-break: break-all;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}
.handleItem {
  display: flex;
  flex-direction: row;
  align-items: center;
  object-fit: contain;
}
.editIcon,
.addIcon,
.writeIcon {
  width: 16px;
  margin: 0 3px;
  height: 16px;
  cursor: pointer;
}
.deleteIcon {
  width: 16px;
  margin-right: 10px;
  margin-left: 3px;
  height: 16px;
  cursor: pointer;
}
</style>

<style scoped lang="scss">
.top-btn {
  width: 127px;
  height: 40px;
  background: rgba(255, 255, 255, 0.3);
  border-radius: 3px;
  border: 1px solid #ffffff;
  font-weight: 400;
  font-size: 16px;
  color: #333333;
  line-height: 40px;
}
:deep(.edui-editor) {
  width: auto !important;
}
:deep(.edui-editor-iframeholder) {
  width: auto !important;
}
#catalog_box ul {
  margin: 0px;
  padding: 0px 0px 0px 20px;
}
.catalog {
  width: 310px;
  height: 632px;
  //margin-right: 4px;
  background: white;
  border-radius: 2px;
  z-index: 900;
}
.content-box {
  flex: 1;
}
#document_editor {
  width: 100%;
  border: 1px solid #cccccc;
}
#catalog_wrapper {
  padding: 15px 0 15px 7px;
  width: 100%;
}
.top_title_box {
  display: flex;
  flex-direction: row;
  align-items: center;
  padding-bottom: 3px;
  border-bottom: 1px dashed #ccc;
  background: #ffffff;
  position: sticky;
  top: 0;
  .catalog_title {
    font-weight: bold;
    font-size: 18px;
    margin-left: 8px;
    line-height: 25px;
  }
}
:deep(.n-spin) {
  width: auto;
  height: auto;
}
.catalog-list {
  list-style: none;
  //height: 705px;
  //overflow-y: auto;
}
.label-box {
  width: 340px;
  height: 632px;
  padding: 15px 0 15px 7px;
  background-color: white;
  .label-item-box {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    padding: 10px 7px 10px 7px;
    border-bottom: 1px dashed #ccc;
    cursor: pointer;
    .label-box-item {
      display: flex;
      flex-wrap: wrap;
      align-items: center;
      width: 100%;
      padding: 3px 7px;
    }
    .label-item {
      display: flex;
      flex-direction: row;
      align-items: center;
      margin: 5px;
      padding: 15px 12px;
      cursor: pointer;
      border-radius: 4px;
      .label-text {
        font-weight: 400;
        font-size: 16px;
        line-height: 18px;
        margin-right: 5px;
      }
      .label-img {
        width: 10px;
        height: 10px;
        margin: 0 5px;
      }
    }
    .label-add-img {
      margin: 5px 5px 5px 15px;
      width: 22px;
      height: 22px;
      cursor: pointer;
    }
  }
}
.search-box {
  width: 340px;
  height: 632px;
  padding: 15px 0 15px 7px;
  background-color: white;
  border-left: 1px solid #e5e7eb;
  .tag-box {
    display: flex;
    flex-direction: row;
    align-items: center;
    padding: 12px 0;
    .tag-line {
      width: 4px;
      height: 14px;
      background: #816cfe;
    }
    .tag-text {
      margin-left: 5px;
      font-weight: 500;
      font-size: 16px;
      color: #333333;
      line-height: 20px;
    }
  }
  .filter-box {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 96px;
    height: 36px;
    background: #e99d42;
    border-radius: 4px;
    color: red;
    .check-label-one {
      :deep(.n-checkbox__label) {
        color: #e99d42 !important;
      }
    }
    .check-label-two {
      :deep(.n-checkbox__label) {
        color: #b11203 !important;
      }
    }
    .check-label-three {
      :deep(.n-checkbox__label) {
        color: #022fd3 !important;
      }
    }
    .check-label-four {
      :deep(.n-checkbox__label) {
        color: #81b337 !important;
      }
    }
    .check-label-five {
      :deep(.n-checkbox__label) {
        color: #7829f5 !important;
      }
    }
  }
  .sentence-item {
    margin: 10px 5px 10px 0;
    font-weight: 400;
    font-size: 14px;
    color: #333333;
    line-height: 25px;
    cursor: pointer;
    background-color: #f7f7f7;
  }
}
</style>
